package com.example.day05.dao;

import com.example.day05.pojos.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wuyunbin
 */
@Component
@Slf4j
public class CategoryMapper {
    /**
     * 新增分类
     * @param category 分类对象
     * @return false-新增不成功 true-新增成功
     */
    public boolean add(Category category){
        //实现对数据库的写入
        try{
            //加载驱动-jdbc
            Class.forName("com.mysql.cj.jdbc.Driver");
            // url?
            //连接数据库
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/blog", "root", "root");
            //执行sql语句
            Statement statement = conn.createStatement();
            boolean result = statement.execute("insert into `category` (`name`) values('"+category.getName()+"') ");
            conn.close();
            log.info("{}",result);
        }catch (Exception e){
            e.printStackTrace();
        }
        //接收处理结果
        return false;
    }


    public List<Category> findAll(){
        List<Category> categories=new ArrayList<>();
        try{
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/blog","root","root");
            //执行
            Statement statement = conn.createStatement();
            String sql="select * from `category`";
            ResultSet resultSet = statement.executeQuery(sql);
            //处理结果
            while (resultSet.next()){
                //取值
                int id = resultSet.getInt("id");
                String name= resultSet.getString("name");
                //封装
                Category category=new Category(id,name);
                //放到list中
                categories.add(category);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return categories;
    }
}
